package com.zzy.serviceimpl.amq;

import com.alibaba.fastjson.JSON;
import com.zzy.service.ActiveMQService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.connection.CachingConnectionFactory;
import java.util.Map;

@Service
public class ActiveMQServiceImpl2 implements ActiveMQService {

    private static final Logger logger = LoggerFactory.getLogger(ActiveMQServiceImpl2.class);




    @Resource(name = "connectionFactory")
    private CachingConnectionFactory connectionFactory;

    private JmsTemplate jmsTemplate;

    //目的地队列的明证，我们要向这个队列发送消息
    private Destination destinationQueue;

    //目的地队列的明证，我们要向这个队列发送消息
    private Destination destinationTopic;


    public ActiveMQServiceImpl2(){
        this.destinationQueue = new org.apache.activemq.command.ActiveMQQueue("spring-queue");
        this.destinationTopic = new org.apache.activemq.command.ActiveMQTopic("spring-topic");
        this.jmsTemplate.setConnectionFactory(connectionFactory);
    }








    @Override
    public void sendQueueMsg(Map map) {
        final String msg = JSON.toJSONString(map);
        try {
            logger.info("将要向队列{}发送的消息msg:{}", destinationQueue, msg);
            jmsTemplate.send(destinationQueue, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createTextMessage(msg);
                }
            });
        } catch (Exception ex) {
            logger.error("向队列{}发送消息失败，消息为：{}", destinationQueue, msg);
        }
    }

    @Override
    public String getQueueMsg(String name) {
        Object msg = jmsTemplate.receiveAndConvert();
        String result = "";
        if(msg!=null){
            result = msg.toString();
        }
        return result;
    }

    @Override
    public void sendTopicMsg(Map map) {
        final String msg = JSON.toJSONString(map);
        try {
            logger.info("将要向Topic发送的消息"+msg, destinationTopic, msg);
            jmsTemplate.send(destinationTopic, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createTextMessage(msg);
                }
            });
        } catch (Exception ex) {
            logger.error("向Topic发送消息失败，消息为："+msg, destinationTopic, msg);
        }
    }


}
